// pages/record-detail/record-detail.js
const app = getApp()

Page({
  data: {
    record: null,
    loading: true,
    showReuploadModal: false,
    reuploading: false
  },

  onLoad(options) {
    console.log('record-detail onLoad, options:', options)
    
    if (options.record) {
      try {
        const recordData = JSON.parse(decodeURIComponent(options.record))
        this.setData({
          record: recordData,
          loading: false
        })
        
        // 调试信息
        console.log('详情页面数据设置完成:', {
          images: recordData.images,
          reject_images: recordData.reject_images,
          reject_videos: recordData.reject_videos
        })
        
        // 格式化审核时间
        if (recordData.audit_time) {
          this.setData({
            'record.audit_time_text': this.formatTime(recordData.audit_time)
          })
        }
        
        // 数据已经是从API获取的正确格式，不需要额外处理
        
      } catch (error) {
        console.error('解析记录数据失败:', error)
        wx.showToast({
          title: '数据解析失败',
          icon: 'none'
        })
        this.setData({
          loading: false
        })
      }
    } else {
      wx.showToast({
        title: '缺少记录数据',
        icon: 'none'
      })
      this.setData({
        loading: false
      })
    }
  },

  // 处理图片数据
  processImages(record) {
    let images = []
    let rejectImages = []
    
    // 处理普通报工图片
    if (record.images) {
      if (typeof record.images === 'string') {
        try {
          images = JSON.parse(record.images)
        } catch (e) {
          images = [record.images]
        }
      } else if (Array.isArray(record.images)) {
        images = record.images
      }
    }
    
    // 处理不良图片
    if (record.reject_images) {
      if (typeof record.reject_images === 'string') {
        try {
          rejectImages = JSON.parse(record.reject_images)
        } catch (e) {
          rejectImages = [record.reject_images]
        }
      } else if (Array.isArray(record.reject_images)) {
        rejectImages = record.reject_images
      }
    }
    
    // 更新数据，但不要覆盖已有的数据
    const updateData = {}
    if (images.length > 0) {
      updateData['record.images'] = images
    }
    if (rejectImages.length > 0) {
      updateData['record.reject_images'] = rejectImages
    }
    
    if (Object.keys(updateData).length > 0) {
      this.setData(updateData)
    }
  },

  // 处理视频数据
  processVideos(record) {
    let videos = []
    let rejectVideos = []
    
    // 处理普通报工视频
    if (record.videos) {
      if (typeof record.videos === 'string') {
        try {
          videos = JSON.parse(record.videos)
        } catch (e) {
          videos = [record.videos]
        }
      } else if (Array.isArray(record.videos)) {
        videos = record.videos
      }
    }
    
    // 处理不良视频
    if (record.reject_videos) {
      if (typeof record.reject_videos === 'string') {
        try {
          rejectVideos = JSON.parse(record.reject_videos)
        } catch (e) {
          rejectVideos = [record.reject_videos]
        }
      } else if (Array.isArray(record.reject_videos)) {
        rejectVideos = record.reject_videos
      }
    }
    
    this.setData({
      'record.videos': videos,
      'record.reject_videos': rejectVideos
    })
  },

  // 格式化时间
  formatTime(timestamp) {
    if (!timestamp) return ''
    const date = new Date(timestamp * 1000)
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit'
    })
  },

  // 预览图片
  previewImage(e) {
    const { urls, current } = e.currentTarget.dataset
    wx.previewImage({
      current: current,
      urls: urls
    })
  },

  // 播放视频
  playVideo(e) {
    const video = e.currentTarget.dataset.video
    if (!video) return
    
    // 如果是字符串，直接播放
    if (typeof video === 'string') {
      wx.previewMedia({
        sources: [{
          url: video,
          type: 'video'
        }]
      })
    } else if (video.url) {
      // 如果是对象，使用url字段
      wx.previewMedia({
        sources: [{
          url: video.url,
          type: 'video'
        }]
      })
    }
  },

  // 刷新详情
  refreshDetail() {
    wx.showToast({
      title: '刷新成功',
      icon: 'success'
    })
  },

  // 返回上一页
  goBack() {
    wx.navigateBack()
  },

  // 分享
  onShareAppMessage() {
    return {
      title: '报工记录详情',
      path: '/pages/record-detail/record-detail'
    }
  },

  // 显示重新上传模态框
  showReuploadModal() {
    // 初始化产品编号的新图片数组
    const productItems = this.data.record.product_items || []
    const updatedProductItems = productItems.map(item => ({
      ...item,
      newImages: [],
      reuploaded: false
    }))
    
    this.setData({
      showReuploadModal: true,
      'record.product_items': updatedProductItems
    })
  },

  // 隐藏重新上传模态框
  hideReuploadModal() {
    this.setData({
      showReuploadModal: false
    })
  },

  // 阻止事件冒泡
  stopPropagation() {
    // 阻止模态框内容区域的点击事件冒泡
  },

  // 选择新图片
  chooseNewImage(e) {
    const itemNo = e.currentTarget.dataset.itemNo
    const productItems = this.data.record.product_items || []
    
    wx.chooseImage({
      count: 9,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        const tempFilePaths = res.tempFilePaths
        const updatedProductItems = productItems.map(item => {
          if (item.item_no === itemNo) {
            const newImages = [...(item.newImages || []), ...tempFilePaths]
            return {
              ...item,
              newImages: newImages.slice(0, 9) // 最多9张图片
            }
          }
          return item
        })
        
        this.setData({
          'record.product_items': updatedProductItems
        })
      },
      fail: (error) => {
        console.error('选择图片失败:', error)
        wx.showToast({
          title: '选择图片失败',
          icon: 'none'
        })
      }
    })
  },

  // 删除新图片
  deleteNewImage(e) {
    const itemNo = e.currentTarget.dataset.itemNo
    const index = e.currentTarget.dataset.index
    const productItems = this.data.record.product_items || []
    
    const updatedProductItems = productItems.map(item => {
      if (item.item_no === itemNo) {
        const newImages = [...(item.newImages || [])]
        newImages.splice(index, 1)
        return {
          ...item,
          newImages
        }
      }
      return item
    })
    
    this.setData({
      'record.product_items': updatedProductItems
    })
  },

  // 提交重新上传
  submitReupload() {
    const productItems = this.data.record.product_items || []
    const itemsToUpload = productItems.filter(item => item.newImages && item.newImages.length > 0)
    
    if (itemsToUpload.length === 0) {
      wx.showToast({
        title: '请至少为一个产品编号上传图片',
        icon: 'none'
      })
      return
    }
    
    this.setData({
      reuploading: true
    })
    
    // 显示加载提示
    wx.showLoading({
      title: '上传中...',
      mask: true
    })
    
    // 逐个上传产品编号的图片
    this.uploadProductImages(itemsToUpload, 0)
  },

  // 递归上传产品图片
  uploadProductImages(items, index) {
    if (index >= items.length) {
      // 所有图片上传完成
      wx.hideLoading()
      this.setData({
        reuploading: false,
        showReuploadModal: false
      })
      
      wx.showToast({
        title: '重新上传成功',
        icon: 'success'
      })
      
      // 刷新页面数据
      this.refreshDetail()
      return
    }
    
    const item = items[index]
    const itemNo = item.item_no
    const images = item.newImages
    
    // 上传当前产品编号的图片
    this.uploadImagesForItem(itemNo, images, () => {
      // 当前产品编号上传完成，继续下一个
      this.uploadProductImages(items, index + 1)
    })
  },

  // 上传单个产品编号的图片
  uploadImagesForItem(itemNo, images, callback) {
    if (images.length === 0) {
      callback()
      return
    }
    
    // 逐个上传图片
    this.uploadSingleImage(itemNo, images, 0, callback)
  },

  // 递归上传单张图片
  uploadSingleImage(itemNo, images, index, callback) {
    if (index >= images.length) {
      callback()
      return
    }
    
    const imagePath = images[index]
    
    // 上传图片到服务器
    wx.uploadFile({
      url: app.globalData.apiUrl + '/api/userex/reuploadReportImage',
      filePath: imagePath,
      name: 'image',
      formData: {
        report_id: this.data.record.id,
        item_no: itemNo
      },
      success: (res) => {
        try {
          const result = JSON.parse(res.data)
          if (result.code === 1) {
            // 上传成功，继续下一张
            this.uploadSingleImage(itemNo, images, index + 1, callback)
          } else {
            throw new Error(result.msg || '上传失败')
          }
        } catch (error) {
          console.error('上传图片失败:', error)
          wx.hideLoading()
          this.setData({
            reuploading: false
          })
          wx.showToast({
            title: '上传失败: ' + error.message,
            icon: 'none'
          })
        }
      },
      fail: (error) => {
        console.error('上传图片失败:', error)
        wx.hideLoading()
        this.setData({
          reuploading: false
        })
        wx.showToast({
          title: '上传失败',
          icon: 'none'
        })
      }
    })
  }
})
